package cn.com.libertymutual.core.redis.config;

import java.time.Duration;

import javax.annotation.Resource;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration.JedisClientConfigurationBuilder;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import redis.clients.jedis.JedisPoolConfig;


@Configuration
public class JedisClusterConfig {

	///private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$"); 
	
	@Autowired
	private RedisProperties redisProperties;
	
	@Autowired
	private JedisPoolConfig jedisPoolConfig;
	

	/**
	* 注意：
	* 这里返回的JedisCluster是单例的，并且可以直接注入到其他类中去使用
	* @return
	*/
	@Bean(name="jedisConnectionFactory", destroyMethod="destroy")
	public JedisConnectionFactory newJedisConnectionFactory() {
		/*String[] serverArray = redisProperties.getClusterNodes().split(",");//获取服务器数组(这里要相信自己的输入，所以没有考虑空指针问题)
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
        	String[] ipPortPair = ipPort.split(":");
        	nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
		 */

		JedisClientConfigurationBuilder jedisClientConfigurationBuilder = JedisClientConfiguration.builder().usePooling().poolConfig( jedisPoolConfig ).and();

		if( redisProperties.getConnectTimeout() != 0 ) {
			jedisClientConfigurationBuilder.connectTimeout(Duration.ofMinutes(redisProperties.getConnectTimeout()));
		}
		if( redisProperties.getReadTimeout() != 0 ) {
			jedisClientConfigurationBuilder.readTimeout(Duration.ofMinutes(redisProperties.getReadTimeout()));
		}
		
		JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(getRedisClusterConfiguration(), jedisClientConfigurationBuilder.build());

        return jedisConnectionFactory;
	}
	
	private RedisClusterConfiguration getRedisClusterConfiguration( ) {
		//String[] serverArray = redisProperties.getClusterNodes().split(",");//获取服务器数组(这里要相信自己的输入，所以没有考虑空指针问题)
		
		RedisClusterConfiguration rcc = new RedisClusterConfiguration( redisProperties.getClusterNodes() );
		
		if( redisProperties.getPassword() != null && redisProperties.getPassword().length()>2 )
			rcc.setPassword(RedisPassword.of(redisProperties.getPassword()));
		
		/*String[] ipPortPair = null;
		boolean isIpPort = false;
		for (String ipPort : redisProperties.getClusterNodes()) {
			isIpPort = p.matcher(ipPort).matches();  
			  
            if (!isIpPort) {  
                throw new IllegalArgumentException("ip 或 port 不合法");  
            }  
            
        	ipPortPair = ipPort.split(":");
        	rcc.addClusterNode( new RedisNode(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())) );
        }
        **/
		
		if( redisProperties.getMaxRedirects() != 0 )
			rcc.setMaxRedirects(redisProperties.getMaxRedirects());
			
		return rcc;
	}
	
	@Bean
	@ConfigurationProperties(prefix="spring.redis")
	public JedisPoolConfig getJedisPoolConfig() {
		//JedisPoolConfig jpc = new JedisPoolConfig();
		
		return new JedisPoolConfig();
	}
	
	@Bean
	public RedisCacheManager getRedisCacheManager( @Qualifier("jedisConnectionFactory") JedisConnectionFactory jedisConnectionFactory ) {
		
		return RedisCacheManager.create( jedisConnectionFactory );

	}
}
